import api from '@/api';
import router from '@/router';
import { defineStore } from 'pinia';
import localMenus from '@/utils/local-menus';
import { handleMenus } from '@/utils/menus-helper';

export const useMenuStore = defineStore('menu', {
  state: () => ({
    tabs: [],
    activeTab: '',
    menus: [],
  }),
  actions: {
    setactiveTab(path: string) {
      this.activeTab = path;
    },
    addTab(tab) {
      this.tabs.push(tab);
    },
    removeTab(tabPath: string) {
      const { tabs, activeTab } = this;
      const index = tabs.findIndex((it) => it.path === tabPath);
      // 如果就剩1个tab 不让删除
      if (tabs.length > 1) {
        tabs.splice(index, 1);
        // 删除当前tab若是处于激活状态后 还要激活一个新的标签
        if (tabPath === activeTab) {
          if (tabs.length === 1) {
            router.push(tabs[0].path);
          } else {
            // 如果在最左边则激活右边的
            if (index === 1) {
              router.push(tabs[index + 1].path);
            } else {
              router.push(tabs[index - 1].path);
            }
          }
        }
      }
    },

    clearTabs() {
      this.tabs = [];
    },
    async syncMenu() {
      const data = await api.getMenus();
      const menus = handleMenus([...localMenus, ...data]);
      this.menus = menus;
    },
  },
  persist: true,
});
